<template>
  <div>
    <!-- 面包屑导航 -->
    <breadcrumbs :data1="data1" :data2="data2"></breadcrumbs>
    <el-card>
      <!-- 头部警告框 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <!-- 选择分类相关代码 -->
      <el-row class="cat_opt">
        <el-col>
          <span>请选择分类：</span>
          <el-cascader
            v-model="selectedCateKeys"
            :options="catelist"
            clearable
            :props="{ expandTrigger: 'hover',value:'cat_id',label:'cat_name',children:'children' }"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <el-row>
        <!-- Tabs标签页 -->
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="动态参数" name="many">
            <!-- 添加参数的按钮 -->
            <el-button
              type="primary"
              size="mini"
              :disabled="isBtnDisabled"
              @click="addParamsdialogVisible = true"
            >添加参数</el-button>
            <!-- 动态参数的表格 -->
            <el-table :data="manyTableData" style="width: 100%" border stripe>
              <!-- type="expand" 表格中的展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    v-for="(item, i) in scope.row.attr_vals"
                    :key="i"
                    closable
                    @close="handleClose(i, scope.row)"
                  >{{item}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  ></el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                  >+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="编号" width="60"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-edit"
                    @click="editParamsBtn(scope.row.attr_id)"
                  >编辑</el-button>
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="delParams(scope.row.attr_id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="only">
            <el-button
              type="primary"
              size="mini"
              :disabled="isBtnDisabled"
              @click="addParamsdialogVisible = true"
            >添加属性</el-button>
            <!-- 静态属性的表格 -->
            <el-table :data="onlyTableData" style="width: 100%" border stripe>
              <!-- type="expand" 表格中的展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    v-for="(item, i) in scope.row.attr_vals"
                    :key="i"
                    closable
                    @close="handleClose(i, scope.row)"
                  >{{item}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  ></el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                  >+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="编号" width="60"></el-table-column>
              <el-table-column label="属性名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-edit"
                    @click="editParamsBtn(scope.row.attr_id)"
                  >编辑</el-button>
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="delParams(scope.row.attr_id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-row>
      <!-- 添加属性的对话框 -->
      <el-dialog
        :title="'添加'+ titleText"
        :visible.sync="addParamsdialogVisible"
        width="50%"
        @close="closeForm"
      >
        <el-form
          :model="addParamsInfo"
          :rules="addParamsrules"
          ref="addParamsForm"
          label-width="110px"
        >
          <el-form-item :label="titleText+':'" prop="attr_name">
            <el-input v-model="addParamsInfo.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="addParamsdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改属性的对话框 -->
      <el-dialog :title="'修改'+ titleText" :visible.sync="editParamsdialogVisible" width="50%">
        <el-form
          :model="editParamsInfo"
          :rules="addParamsrules"
          ref="editParamsForm"
          label-width="110px"
        >
          <el-form-item :label="titleText+':'" prop="attr_name">
            <el-input v-model="editParamsInfo.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="editParamsdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
           
<script>
import breadcrumbs from '@/common/breadcrumbs.vue'
import { log } from 'util';
export default {
  data () {
    return {
      data1: '商品管理',
      data2: '参数列表',
      catelist: [],
      selectedCateKeys: [],
      manyTableData: [],
      onlyTableData: [],
      cateParamsId: 0,
      attrId: 0,
      activeName: 'many',
      addParamsdialogVisible: false,
      editParamsdialogVisible: false,
      addParamsInfo: {
        attr_name: ''
      },
      editParamsInfo: {
        attr_name: ''
      },
      // 添加/修改属性的验证规则
      addParamsrules: {
        attr_name: [
          { required: true, message: `名称不能为空!`, trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ],
      }
    }
  },
  components: {
    breadcrumbs
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status === 200) {
        this.catelist = res.data
      } else {
        this.$message.error(res.meta.msg)
      }
    },
    handleChange () {
      if (this.selectedCateKeys.length != 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
      } else {
        this.cateParamsId = this.selectedCateKeys[this.selectedCateKeys.length - 1]
        this.getCateParams()
      }
    },
    async getCateParams () {
      const { data: res } = await this.$http.get(`categories/${this.cateParamsId}/attributes`, { params: { sel: this.activeName } })
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName == 'many') {
        this.manyTableData = res.data
        // console.log(this.manyTableData)
      } else {
        this.onlyTableData = res.data
        // console.log(this.onlyTableData)
      }
    },
    handleClick () {
      if (!this.isBtnDisabled) {
        this.getCateParams()
      }
    },
    closeForm () {
      this.$refs.addParamsForm.resetFields()
    },
    async addParams () {
      this.$refs.addParamsForm.validate(async val => {
        if (val) {
          const { data: res } = await this.$http.post(`categories/${this.cateParamsId}/attributes`, {
            attr_name: this.addParamsInfo.attr_name, attr_sel: this.activeName
          })
          if (res.meta.status == 201) {
            this.getCateParams()
            this.$message.success('添加成功~~')
            this.addParamsdialogVisible = false
          } else {
            this.$message.error(res.meta.msg)
          }
        }
      })
    },
    async editParamsBtn (id) {
      this.attrId = id
      const { data: res } = await this.$http.get(`categories/${this.cateParamsId}/attributes/${this.attrId}`, {
        params: { attr_sel: this.activeName }
      })
      if (res.meta.status == 200) {
        this.editParamsdialogVisible = true
        this.editParamsInfo.attr_name = res.data.attr_name
      } else {
        this.$message.error(res.meta.msg)
      }
    },
    async editParams () {
      this.$refs.editParamsForm.validate(async val => {
        if (val) {
          const { data: res } = await this.$http.put(`categories/${this.cateParamsId}/attributes/${this.attrId}`, {
            attr_name: this.editParamsInfo.attr_name, attr_sel: this.activeName
          })
          if (res.meta.status == 200) {
            this.editParamsdialogVisible = false
            this.getCateParams()
            this.$message.success('修改成功~~')
          } else {
            this.$message.error(res.meta.msg)
          }
        }
      })
    },
    delParams (id) {
      this.$confirm('此操作将永久删除该属性, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`categories/${this.cateParamsId}/attributes/${id}`)
        if (res.meta.status == 200) {
          this.$message.success('删除成功~~')
          this.getCateParams()
        } else {
          this.$message.error(res.meta.msg)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '用户取消删除操作'
        });
      });
    },
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length == 0) {
        row.inputValue = ''
        row.inputVisible = false
      } else {
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false
        const { data: res } = await this.$http.put(`categories/${this.cateParamsId}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(' ')
        })
        if (res.meta.status == 200) {
          this.$message.success('添加成功~')
        } else {
          this.$message.error(res.meta.msg)
        }
      }
    },
    showInput (row) {
      row.inputVisible = true
      // 文本框自动获得焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async handleClose (i, row) {
      row.attr_vals.splice(i, 1)
      const { data: res } = await this.$http.put(`categories/${this.cateParamsId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status == 200) {
        this.$message.success('删除成功~')
      } else {
        this.$message.error(res.meta.msg)
      }
    }
  },
  created () {
    this.getCateList()
  },
  computed: {
    isBtnDisabled () {
      if (this.selectedCateKeys.length == 3) {
        return false
      } else {
        return true
      }
    },
    titleText () {
      if (this.activeName == 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>
<style scoped lang='less'>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin-right: 12px;
}
.input-new-tag {
  width: 130px;
}
</style>